package fr.licpro.filebox.service;

import retrofit.RestAdapter;
import retrofit.RestAdapter.LogLevel;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import fr.licpro.filebox.service.json.JacksonConverter;
import fr.licpro.filebox.utils.CustomErrorHandler;
import fr.licpro.filebox.utils.FileboxConstant;


/**
 * Service for sync data
 */
public class SyncService extends IntentService {
	/**
	 * SyncService Tag for Log 
	 */
	@SuppressWarnings("unused")
	private static final String TAG = SyncService.class.getSimpleName();
	
	/**
	 * Data in the intent
	 */
	public static final String SYNC_CLASS_INTENT = "fr.licpro.filebox.syncData";

	/**
	 * REST client
	 */
	protected IRestClient mRestClient;

	/**
	 * Service constructor
	 */
	public SyncService() {
		super(SyncService.class.getSimpleName());
	}
	
	@Override
	public void onCreate() 
	{
		super.onCreate();
		
		 // Create a very simple REST adapter which points the GitHub API endpoint.
	    RestAdapter restAdapter = new RestAdapter.Builder()
	    	.setLogLevel(LogLevel.FULL)
	    	.setErrorHandler(new CustomErrorHandler(getApplicationContext()))
	        .setEndpoint(FileboxConstant.URL_SERVER)
	        .setConverter(new JacksonConverter())
	        .build();

	    // Create an instance of our IRestClient API interface.
	    mRestClient = restAdapter.create(IRestClient.class);
	}

	@Override
	protected void onHandleIntent(final Intent pIntent) {
		ISync sync = (ISync) pIntent.getParcelableExtra(SYNC_CLASS_INTENT);
		sync.execute(getApplicationContext(), mRestClient);
	}
	
	/**
	 * Check if Network is reachable
	 * @param pContext Application context
	 * @return True if yes
	 */
	public static boolean isNetworkAvailable(final Context pContext)
	{
		ConnectivityManager cm = (ConnectivityManager)pContext.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = cm.getActiveNetworkInfo();
		return info != null && info.isConnectedOrConnecting();
	}
}
